package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.dto.QuestionDTO;
import com.demo.dto.Result;
import com.demo.dto.UserDTO;
import com.demo.entity.Question;
import com.demo.mapper.QuestionMapper;
import com.demo.query.QuestionQuery;
import com.demo.service.QuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.utils.UserHolder;
import com.demo.vo.QuestionVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zeng
 * @since 2022-03-23
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Override
    public Result<Question> postQuestion(QuestionDTO questionDTO) {
        Question question = BeanUtil.copyProperties(questionDTO, Question.class);
        // TODO: 检验问题是否有问题（未完成）
        //
        // 获取当前用户，即提问的用户
        Integer userId = UserHolder.getUser().getUserId();
        question.setUserId(userId);

        if (!save(question)) {
            return Result.fail("问题新建失败");
        }
        return Result.ok(getById(question.getQuestionId()));
    }



    @Override
    public Result<Question> putQuestion(Integer questionId, QuestionDTO questionDTO) {
        Question question = BeanUtil.copyProperties(questionDTO, Question.class);
        // 查看用户有没有修改问题的权限，这里只有此问题是该用户发表的才能被其修改
        Integer userId = UserHolder.getUser().getUserId();
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", questionId)
                .eq("user_id", userId);
        boolean update = update(question, queryWrapper);
        if (!update) {
            return Result.fail("该用户没有此问题的修改权限");
        }
        return Result.ok(getById(questionId));
    }

    @Override
    public Result<List<QuestionVO>> queryQuestionsByKeyword(QuestionQuery questionQuery) {
        Integer userId = UserHolder.getUser() == null ? null : UserHolder.getUser().getUserId();
        questionQuery.setUserId(userId);
        List<QuestionVO> questions = baseMapper.queryQuestionsByKeyword(questionQuery);
        if (questions.isEmpty()) {
            return Result.fail("当前问题为空");
        }
        return Result.ok(questions, questions.size());
    }
}
